﻿using DevExpress.ClipboardSource.SpreadsheetML;
using DMSkin.Socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HTHMachineVision
{
    /// <summary>
    /// TCP服务类
    /// </summary>
    public class TCPService
    {
        //服务器对象
        public DMTcpServer m_TcpServer = new DMTcpServer();
        //客户端对象
        DMTcpClient m_TcpClient = new DMTcpClient();

        //记录连接机器人的ip
        string tcpClientIp = "192.168.3.11";
        //string tcpClientIp = "127.0.0.1"; //本地测试
        int tcpClienPort = 5000;
       

        //服务端
        public string serverIp = "127.0.0.1";//IP
        public int serverPort = 9000;//端口号

        //客户端连接服务器标志
        public bool m_IsConnected = false;

        public event EventHandler<string> DataReceived;

        /// <summary>
        /// 开启服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void StartSever()
        {
            //服务器IP
            m_TcpServer.ServerIp = serverIp;
            m_TcpServer.ServerPort = serverPort;
            //开启服务器
            m_TcpServer.Start();
        }

        

        /// <summary>
        /// 关闭服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CloseServer()
        {
            m_TcpServer.Stop();
        }


        /// <summary>
        /// 服务端发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ServerSendMessage(string msg)
        {
            //客户端的 端口号是由服务器分配的，通过监听上线事件获得
            m_TcpServer.SendData(serverIp, serverPort, msg);
        }

        /// <summary>
        /// 窗口关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void FormClosing()
        {
            CloseServer();
            ClientClose();
        }

  

        /// <summary>
        /// 连接服务器(机器人)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnlineServe()
        {
            try
            {
                m_TcpClient.ServerIp = tcpClientIp;
                m_TcpClient.ServerPort = tcpClienPort;

                //接受服务器信息
                m_TcpClient.OnReceviceByte += M_TcpClient_OnReceviceByte;
                //监听服务器状态
                m_TcpClient.OnStateInfo += M_TcpClient_OnStateInfo;

                m_TcpClient.StartConnection();

                m_IsConnected = true;
                MessageBox.Show("机器人已连接！");
               
            }
            catch (Exception)
            {
                m_IsConnected = false;
                MessageBox.Show("机器人连接失败！");
            }
        }

        /// <summary>
        /// 获取客户端连接状态
        /// </summary>
        /// <returns></returns>
        public bool GetClientState()
        {
            if(!m_IsConnected)
            {
               return false;
            }
             return true;   
        }

        /// <summary>
        /// 监听服务器状态
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="state"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void M_TcpClient_OnStateInfo(string msg, SocketState state)
        {
            //连接
            if (state == SocketState.Connected)
            {
                m_IsConnected = true;
                WriteLog_Client("连接服务器成功!");
            }
            else
            {
                m_IsConnected = false;
            }

        }

        /// <summary>
        /// 接收服务器信息
        /// </summary>
        /// <param name="date"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void M_TcpClient_OnReceviceByte(byte[] date)
        {
            //发过来的什么东西
            //  GetString byte[]  转换成  String
            //  Replace("\r", "")  -->替换源  \r   替换成 ""
            //  .Trim();  移除字符串  前面与后面的空白符
            string msg = Encoding.Default.GetString(date).Replace("\r", "").Trim();

            char[] vs1 = { ':' };
            string[] vs2 = msg.Split(vs1, StringSplitOptions.RemoveEmptyEntries);
            if (vs2.Length > 0)
            {
                if (Command.data_机器人完成信号 == vs2[0])
                {
                    State.done_机器人到达标定点 = true;
                }
                //获取机器人发送的点位  格式 X:  600.000 Y:    0.000 Z:    0.000 U:    0.000 V:    0.000 W:    0.000 /R /0
                if ("X" == vs2[0])
                {
                    OnDataReceived(msg);
                }

            }
            
            WriteLog_Client(msg);
        }

        /// <summary>
        /// 坐标回调事件
        /// </summary>
        /// <param name="data"></param>
        public void OnDataReceived(string data)
        {
            DataReceived?.Invoke(this, data);
        }

        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ClientClose()
        {
            m_TcpClient.StopConnection();
            //接受服务器信息
            m_TcpClient.OnReceviceByte -= M_TcpClient_OnReceviceByte;
            //监听服务器状态
            m_TcpClient.OnStateInfo -= M_TcpClient_OnStateInfo;
        }

        /// <summary>
        /// 客户端发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ClientSend(string msg)
        {
            if (m_IsConnected)
            {
                m_TcpClient.SendCommand($"{msg}\r\n");
                Console.WriteLine("给机器人发消息：" + msg);


            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog_Client(string msg)
        {
            string str = DateTime.Now.ToString("yyyy_MM_dd HH:mm:ss fff");
            msg = $"{str}: {msg}";

            /*//异步线程写入日志
            textBox_clientLog.BeginInvoke(new Action(() => {
                if (textBox1_ServerLog.TextLength > 1000)
                {
                    textBox_clientLog.Text = "";
                }
                textBox_clientLog.AppendText(msg + "\r\n");
                //翻滚到当前
                textBox_clientLog.SelectionStart = textBox_clientLog.TextLength;
                textBox_clientLog.ScrollToCaret();

            }));*/
        }

    }
}
